package main

import (
	"context"
	"flag"
	"fmt"

	"gozeroSingle/internal/config"
	"gozeroSingle/internal/handler"
	"gozeroSingle/internal/middlewares"
	"gozeroSingle/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/app.yaml", "the config file")

func main() {
	var env string
	// 运行环境
	flag.StringVar(&env, "env", "dev", "运行环境")
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	// 设置环境变量
	c.Env = env

	// 初始化日志
	logx.MustSetup(c.CustomLog)
	// 输出当前环境
	logx.Info(context.Background(), " current environment: "+c.Env)

	defer logx.Close()

	// 创建服务
	server := rest.MustNewServer(c.RestConf)

	// 注册全局 JSON 中间件
	server.Use(middlewares.GlobalJsonMiddleware)

	defer server.Stop()

	// 创建服务上下文
	ctx := svc.NewServiceContext(c)

	// 注册处理器
	handler.RegisterHandlers(server, ctx)

	// 使用单级限流器[PeriodLimiter、TokenLimiter]
	switch ctx.Config.LimiterConf.Mode {
	case "period":
		server.Use(middlewares.PeriodLimiterMiddleware(ctx))
	case "token":
		server.Use(middlewares.TokenLimiterMiddleware(ctx))
	}

	// 使用多级限流器
	// multiLevelRateLimiter := tools.NewMultiLevelRateLimiter(ctx)
	// server.Use(func(next http.HandlerFunc) http.HandlerFunc {
	// 	return func(w http.ResponseWriter, r *http.Request) {
	// 		// 从请求中获取用户ID（实际项目中可能从token中解析）
	// 		uid := r.Header.Get("X-User-ID")
	// 		err := multiLevelRateLimiter.CheckRateLimit(r, uid)
	// 		if err != nil {
	// 			httpx.OkJsonCtx(r.Context(), w, utils.ErrorOutput("人气太火爆了，请稍等", []int{http.StatusTooManyRequests}...))
	// 			return
	// 		}
	// 	}
	// })

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)

	// 启动服务
	server.Start()
}
